package cn.zkdcloud.framework.render;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.zkdcloud.framework.servlet.HttpContext;
import cn.zkdcloud.framework.util.Proty;
import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;

public class FreemarkerRender extends AbstractRender{

	private static Configuration config = new Configuration(Configuration.VERSION_2_3_23);

	private Template template;
	static{
		try{
			config.setDefaultEncoding("UTF-8");
			config.setDirectoryForTemplateLoading(new File(Proty.getFreemarkerPath()));
		}catch(Exception e){
			System.out.println("配置freemarker失败");
		}

	}

	public FreemarkerRender(String path){
		try {
			template = config.getTemplate(path);
		} catch (TemplateNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedTemplateNameException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**execute render
	 *
	 * @param context HttpContext
	 */
	public void doRender(HttpContext context) {
		HttpServletResponse response = context.getResponse();
		HttpServletRequest request = context.getRequest();
		HttpSession session = request.getSession();

		super.getModelMap().put("server", request.getAttribute("server"));//add server ,so we can use ${server} replace host
		Enumeration enumeration = session.getAttributeNames();//put parameter of session to freemarker var
		while(enumeration.hasMoreElements()){
			String name = enumeration.nextElement().toString();
			super.getModelMap().put(name,session.getAttribute(name));
		}
		try {
			response.setContentType("text/html");
			response.setCharacterEncoding("UTF-8");
			response.setHeader( "Cache-Control" , "no-store" );
			template.process(super.getModelMap(), response.getWriter());

		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}



}
